<?php
/**
 * 微信/小程序用户信息
 * @author maniac
 */
namespace app\common\service;

use app\common\logic\Dump;
use app\common\model\ActivityGoods;
use app\common\model\MemberRecharge as MemberRechargeModel;
use app\common\model\MemberBalance as MemberBalanceModel;
use app\common\model\Members;
use app\common\model\WechatUsers;
use app\common\model\UsersAuthlogin;
use app\common\model\Members AS MembersModel;
use app\common\model\MemberData;
use app\common\model\Buycar;
use app\facade\Aes AS AesFacade;
use app\facade\Members AS MembersFacade;
use app\facade\Options AS OptionsFacade;
use app\common\model\MemberPoints AS MemberPointsModel;
use app\common\model\Orders AS OrdersModel;
use app\common\model\OrderGoods AS OrderGoodsModel;
use app\facade\Site AS SiteFacade;
use app\common\model\Goods AS GoodsModel;
use app\common\model\GoodSku AS GoodSkuModel;
use app\common\model\MemberYongjin as MemberYongjinModel;
use app\common\model\MemberFx;
use app\common\model\OrderBank AS OrderBankModel;

use think\Db;
use think\facade\Env;
use \wxpay\CLogFileHandler;
use \wxpay\Log;
use \wxpay\JsApiPay;
use \wxpay\WxPayUnifiedOrder;
use \wxpay\WxPayApi;
use app\facade\Distribution;


class Wechat extends Base
{
    /**
     * 添加会员
     * @param array $data 请求的信息
     */
    public function add($data)
    {


        if (isset($data['unionid']) && !empty($data['unionid'])) {
            $where = [
                'unionid' => $data['unionid'],
            ];
        } else {
            $where = [
                'openid' => $data['openId'],
            ];
        }
        $parent_id = isset($data['parent_id']) ? $data['parent_id'] : 0;
        // 查看 openid 是否存在
        $encrypt = WechatUsers::field('id,unionid,openid,member_id')->where($where)->find();
        $data['nickname'] = preg_replace_callback('/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $data['nickName']);
        if (!$encrypt) {
            $user = WechatUsers::create([
                'openid' => $data['openId'],
                'nickname' => $data['nickName'],
                'headimgurl' => $data['avatarUrl'],
                'sex' => $data['gender'],
//                'type'=>$data['type'],
                'unionid' => isset($data['unionid']) ? $data['unionid'] : '',
                'figureurl_qq_2' => isset($data['figureurl_qq_2']) ? $data['figureurl_qq_2'] : '',
            ]);
            if ($user->id) {

                $member = MembersModel::create([
                    'wechat_id' => $user->id,
                    'openid' => $data['openId'],
                    'nickname' => $data['nickName'],
                    'image_uri' => $data['avatarUrl'],
                    'points' => 0,
                    'checked' => 1,
                    'status' => 1,
                    'parent_id' => 0//上一级id
                ]);

                if ($member->id) {

                    $user = WechatUsers::update([
                        'id' => $user->id,
                        'member_id' => $member->id,
                    ]);

                    // 会员副表
                    MemberData::create([
                        'id' => $member->id,
                        'login_nums' => 1,
                        'last_login_ip' => request()->ip(),
                        'last_login_time' => time(),
                        'intro' => '',
                    ]);
                    $encrypt = [
                        'id' => $member->id,
                        'unionid' => isset($data['unionid']) ? $data['unionid'] : 0,
                        'openid' => $data['openId'],
                    ];
                } else {
                    exception('添加会员失败');
                }
            } else {
                exception('微信注册失败');
            }
            $userId = $user->id;
        } else {
            $encrypt = $encrypt->toArray();
            WechatUsers::update([
                'id' => $encrypt['id'],
                'openid' => $data['openId'],
                'nickname' => $data['nickName'],
                'headimgurl' => $data['avatarUrl'],
                'sex' => $data['gender'],
//                'type'=>$data['type'],
                'unionid' => isset($data['unionid']) ? $data['unionid'] : '',
                'figureurl_qq_2' => isset($data['figureurl_qq_2']) ? $data['figureurl_qq_2'] : '',
            ]);
            $member = MembersModel::field('id,parent_id')->where('wechat_id', $encrypt['id'])->find();
//            if($parent_id > 0){
//                Distribution::can_offline($encrypt['member_id'],$parent_id);//判断是否可成为下线
//                if ($member['parent_id']==0){
//                    $member->parent_id = $parent_id;
//                    $member->save();
//                }
//            }
            if ($member) {
                $fData = MemberData::field('id,login_nums,last_login_ip,last_login_time')->where('id', $member['id'])->find();
                $fData->login_nums = ['inc', 1];
                $fData->last_login_ip = request()->ip();
                $fData->last_login_time = time();
                // 更新副表信息
                $fData->save();
            }
            $userId = $encrypt['id'];
//            $encrypt['id']=$member['id'];
            $encrypt = [
                'id' => $member['id'],
                'unionid' => $encrypt['unionid'],
                'openid' => $encrypt['openid'],
            ];

        }

        $userToken = AesFacade::encrypt(http_build_query($encrypt));
        $info = $this->info($userToken);
        $info['userToken'] = $userToken;
        $info['membersInfo'] = MembersFacade::info($userId);
        return $info;
    }
    /**
     * 获取用户信息
     * @param string $userToken userToken
     */
    public function info($userToken)
    {

        $decrypt   = AesFacade::decrypt($userToken);
        parse_str($decrypt, $wechat);
        if (!isset($wechat['id']) || !$wechat['id'] || !isset($wechat['openid']) || !$wechat['openid']) {
            exception('用户不存在1');
        }
        $user = Members::field(true)->where('id', $wechat['id'])->find();

        if (!$user) {
            exception('用户不存在2');
        }
        $data = [
            'userInfo' => $user->toArray(),
            'cartNums' => Buycar::where('userid', $user['id'])->count(),
        ];
        return $data;
    }

    /**
     * 获取全局 access_token
     * @return [type] [description]
     */
    public function getAccessToken($flag = true)
    {
        $root = str_replace('\\', '/', Env::get('root_path'));
		$access_token_file = $root . 'static/data/access_token.json';

		if ($flag) {
			if (file_exists($access_token_file)) {
				$data = json_decode(file_get_contents($access_token_file));
				if ($data) {
					if (time() >= $data->expire_time) {
						// 已过期，需要重新生成 access_token
						$flag = false;
					}
				} else {
					$flag = false;
				}
			} else {
				// access_token.json 文件不存在，需要重新生成 access_token
				$flag = false;
			}
		}

        if (!$flag) {
            // 重新生成 access_token
            $data   = json_decode(curl_request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('site.app_id').'&secret='.config('site.app_secret')));

            $temp   = [
                'access_token' => $data->access_token,
                'expire_time'  => time() + $data->expires_in,
            ];
            // 将 access_token 及过期时间 expire_time 写入 access_token.json 文件
            file_put_contents($access_token_file, json_encode($temp));
        }
        return $data->access_token;
    }
    //获取企业
    public function getPyAccessToken($flag = true)
    {
        $root = str_replace('\\', '/', Env::get('root_path'));
        $access_token_file = $root . 'static/data/qy_access_token.json';

        if ($flag) {
            if (file_exists($access_token_file)) {
                $data = json_decode(file_get_contents($access_token_file));
                if ($data) {
                    if (time() >= $data->expire_time) {
                        // 已过期，需要重新生成 access_token
                        $flag = false;
                    }
                } else {
                    $flag = false;
                }
            } else {
                // access_token.json 文件不存在，需要重新生成 access_token
                $flag = false;
            }
        }

        if (!$flag) {
            // 重新生成 access_token
//            $data   = json_decode(curl_request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('site.app_id').'&secret='.config('site.app_secret')));
            $data   = json_decode(curl_request('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.config('site.corpid').'&corpsecret='.config('site.corpsecret')));

            $temp   = [
                'access_token' => $data->access_token,
                'expire_time'  => time() + $data->expires_in,
            ];
            // 将 access_token 及过期时间 expire_time 写入 access_token.json 文件
            file_put_contents($access_token_file, json_encode($temp));
        }
        return $data->access_token;
    }
    public function getJsApiTicket()
    {
        $root = str_replace('\\', '/', Env::get('root_path'));
        $jsapi_ticket_file = $root . 'static/data/jsapi_ticket.json';
        $flag              = true;
        if (file_exists($jsapi_ticket_file)) {
            $data = json_decode(file_get_contents($jsapi_ticket_file));
            if (time() >= $data->expire_time) {
                // 已过期，需要重新生成 jsapi_ticket
                $flag = false;
            }
        } else {
            // jsapi_ticket.json 文件不存在，需要重新生成 jsapi_ticket
            $flag = false;
        }
        if (!$flag) {
            // 重新生成 jsapi_ticket
            $access_token = self::getAccessToken();
            $data   = json_decode(curl_request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$access_token));
            $temp   = [
                'ticket'      => $data->ticket,
                'expire_time' => time() + $data->expires_in,
            ];
            // 将 access_token 及过期时间 expire_time 写入 access_token.json 文件
            file_put_contents($jsapi_ticket_file, json_encode($temp));
        }
        return $data->ticket;
    }

    public function getSignPackage($appId,$appsecret,$url) {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
//    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

	private function createNonceStr($length = 16)

	{

		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

		$str = "";

		for ($i = 0; $i < $length; $i++) {

			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

		}

		return $str;

	}

// 模板消息
    // 用户openid 模板id 消息数组 公众号app_id
    public function sendMessageAll($openId,$templateId,$message,$appid,$url)
    {
        //获取access_token
//        $access_token = WechatFacade::getAccessToken();
        $access_token = $this->getAccessToken();


        //要发送给微信接口的数据
        $send_data = [
            //用户openId
            "touser" => $openId,
            //模板id
            "mp_template_msg" => [
                "appid" => $appid,
                "template_id" => $templateId,

                "miniprogram" => [ //跳转的小程序
                    "appid" => config('site.app_id'),
                    "pagepath" => $url
                ],
                'data'=> $message
            ]
        ];

        $send_data=json_encode($send_data);

        //将路径中占位符%s替换为$access_token值
        $ret = curl_request('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token='.$access_token, $send_data);
        return json_decode($ret);
    }
    /**
     * 微信支付统一下单
     * @param  array $data 订单信息
     */
    public function unifiedorder($data)
    {
        //初始化日志
        $logHandler = new CLogFileHandler("./extend/wxpay/logs/".date('Y-m-d').'.log');
        $log        = Log::Init($logHandler, 15);
        $tools      = new JsApiPay();
//         打赏金额
//        $total_fee  = (float)$data['pay_amount'] * 100;
        $total_fee  = 1;
//        if ($data['openid'] == 'oKb_M4goy5a4mHz_cHIZJXtgXi8M') {
//            $total_fee = 1;
//        }
        // 统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetAppid(config('site.app_id'));
        $input->SetMch_id(config('site.mch_id'));
        $input->SetNonce_str(unid(16));
        $input->SetBody("微信支付");
        $input->SetAttach("");
        $input->SetOut_trade_no("{$data['out_trade_no']}");
        $input->SetTotal_fee("{$total_fee}");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url(config('site.app_uri')."api/v1/notify");
        $input->SetTrade_type("{$data['platform']}");

        if($data['platform']=='JSAPI'){
            $input->SetOpenid($data['openid']);
        }
        $order = WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($order);
        return json_decode($jsApiParameters, true);
    }

    /**
     * 微信支付回调
     * @param  array $data 微信支付返回信息
     */
    public function notify($data)
    {

        $out_trade_no=$data["out_trade_no"];
        $ordrebank      = OrderBankModel::field('id,tableflag,pid,bankpostid,pay_amount,pay_type,pay_status,pay_yue,pay_time,bankretid,ext')
            ->where('bankpostid', $data["out_trade_no"])->find();
        if(!$ordrebank || $ordrebank['pay_status'] == 1){
            return true;
        }
        //更新bank表状态
        $upbank = array(
            'pay_status' => 1,
            'pay_time' => time(),
            'bankretid' => $data['transaction_id'],//微信返回的流水号
            'ext' => json_encode($data),
        );
        OrdersModel::where("order_no",$data["out_trade_no"])->update([
            'pay_status' => 1,
            'pay_time' => time(),
            'transaction_id' => $data['transaction_id'],
        ]);
        $a = OrderBankModel::where("id", $ordrebank["id"])->update($upbank);
        return $this->generateVerificationCode($ordrebank['bankpostid']);
//        if($ordrebank['tableflag'] == 'order'){//购物
//            return $this->orderPayOk($data,0);
//        }
//        if($ordrebank['tableflag'] == 'member_recharge'){//充值
//            return $this->rechargePayOk($data,0);
//        }
    }
    //生成核销码
    public function generateVerificationCode($order_no){
        $orders = OrdersModel::where("order_no",$order_no)->field('id,shipping_method')->find();
        //计算销量
        $this->updateGoodsSaleNums($orders['id']);
        if ($orders['shipping_method'] != 2){
            return true;
        }
        $orderGoods = OrderGoodsModel::where("order_id",$orders['id'])->field('id')->select();
        foreach ($orderGoods as $key => $value){
            $text = request()->domain()."/mob/#/pages/ticket/offs?id=".$value['id'];
            $verification_code =  Qrcode::generateQrcode($text);
            $orderGood = OrderGoodsModel::get($value['id']);
            $orderGood->verification_code = $verification_code;
            $orderGood->save();
        }
        return true;


    }
    public function rechargePayOk($arg,$pay_type){
        $info=MemberRechargeModel::field(true)
            ->where('cz_code',$arg['out_trade_no'])->find();
        if(empty($info)){
            exception('没有此订单');
        }
        try {
            $temp=array(
                'uid'=>$info['cz_uid'],
                'money'=>$info['cz_amount'],
                'pay_type'=>1,
                'points'=>$info['cz_points'],
                'cz_id'  =>$info['cz_id']
            );
            $this->addMoney($temp);
            $d['cz_pay_status'] = 1;
            $d['cz_pay_type'] = 1;
            Db::name('member_recharge')->where('cz_code',$arg['out_trade_no'])->update($d);
            //\app\facade\Members::is_recharge($arg['uid']);
        }catch (\Exception $e){
            exception('出错了');
        }
    }

    public function addMoney($arg){

        $info=Members::field(true)->where('id',$arg['uid'])->find();
        $info->balance = ['Inc', $arg['money']];
        $info->save();

        MemberBalanceModel::create([
            'order_id'  => $arg['cz_id'],
            'userid'    => $arg['uid'],
            'wechat_id' => $arg['uid'],
            'balance'   => +$arg['money'],
            'remark'    => '余额充值',
            'type'    => 3,
        ]);
        return;
    }

    /*
    * 分销
    * @author 董伟 2019.09.12
    * */
    public  function fx($id){
        $info=OrdersModel::field(true)->where('id',$id)->find();
        if(!$info){
            return 0;// 此信息不存在
        }
        if($info['pay_status']==1){
            $orderInfo=OrderGoodsModel::field(true)->where('order_id',$id)->select();
            $cate_arr=array();
            foreach($orderInfo as $k=>$v){
                $type_id=GoodsModel::field(true)->where('id',$v['goods_id'])->column('category_id');
                if(!in_array($type_id,$cate_arr)){
                    $cate_arr[]=$type_id;
                }
            }

            $fx_money=config('system.fx_money');
            $fx_class=config('system.fx_class');
            if($info['pay_amount']>=$fx_money || in_array($fx_class,$cate_arr)){
                //会员升级成为分销商
                $where = [
                    ['id', 'eq', $info['userid']],
                ];
                MembersModel::where($where)->update(['user_rank' => 1]);
                $this->fx_yongjin($info['userid'],$id);
            }
        }
    }

    /*
     * 分销佣金
     * @author 董伟 2019.09.12
    */
    public function fx_yongjin($id,$order_id){


        $orderInfo=OrdersModel::field(true)->where('id',$order_id)->find();
        if(!$orderInfo){
            return 100;
        }
        $pay_amount=$orderInfo['pay_amount']>0?$orderInfo['pay_amount']:0;



        $userinfo=MembersModel::field(true)->where('id',$id)->find();
        if(!$userinfo){
            return 10;
        }
        $fx_money_1=0;
        $fx_money_2=0;
        $fx_money_3=0;

        //一级
        $parent_uid=$userinfo['parent_id'];
        if($parent_uid>0){
            $level_1=MemberFx::field(true)->where('id',$userinfo['user_rank'])->find();
            if($level_1){

                $lv_1=$level_1['fx_1']*0.01;

                $fx_money_1=number_format($lv_1*$pay_amount,2);

                if($fx_money_1>0){

                    $data=array(
                        'order_id'=>$order_id,
                        'userid'=>$parent_uid,
                        'wechat_id'=>$parent_uid,
                        'balance'=>$fx_money_1,
                        'remark'=>'返佣金'
                    );
                    $info = MemberYongjinModel::create($data);
                    $where = [
                        ['id', 'eq', $id],
                    ];
                    MembersModel::where($where)->setInc('money',$fx_money_1);
                }
            }
        }


        //二级
        $userinfo_2=MembersModel::field(true)->where('id',$parent_uid)->find();
        if(!$userinfo_2){
            return 11;
        }
        $parent_uid2=$userinfo_2['parent_id'];
        if($parent_uid2>0){
            $level_2=MemberFx::field(true)->where('id',$userinfo_2['user_rank'])->find();
            if($level_2){
                $lv_2=$level_2['fx_2']*0.01;
                $fx_money_2=number_format($lv_2*$pay_amount,2);
                if($fx_money_2>0){
                    $data=array(
                        'order_id'=>$order_id,
                        'userid'=>$id,
                        'wechat_id'=>$id,
                        'balance'=>$fx_money_2,
                        'remark'=>'返佣金'
                    );
                    $info = MemberYongjinModel::create($data);
                    $where = [
                        ['id', 'eq', $parent_uid2],
                    ];
                    MembersModel::where($where)->setInc('money',$fx_money_2);
                }
            }
        }

        //三级
        $userinfo_3=MembersModel::field(true)->where('id',$parent_uid2)->find();
        if(!$userinfo_3){
            return 13;
        }
        $parent_uid3=$userinfo_3['parent_id'];
        if($parent_uid3>0){
            $level_3=MemberFx::field(true)->where('id',$userinfo_3['user_rank'])->find();
            if($level_3){
                $lv_3=$level_3['fx_3']*0.01;
                $fx_money_3=number_format($lv_3*$pay_amount,2);
                if($fx_money_3>0){
                    $data=array(
                        'order_id'=>$order_id,
                        'userid'=>$id,
                        'wechat_id'=>$id,
                        'balance'=>$fx_money_3,
                        'remark'=>'返佣金'
                    );
                    $info = MemberYongjinModel::create($data);

                    $where = [
                        ['id', 'eq', $parent_uid3],
                    ];
                    MembersModel::where($where)->setInc('money',$fx_money_3);
                }
            }
        }

        return 1;

    }


    /*
     * 购物回调
     * @author 董伟
     * */
    public function orderPayOk($arg){
        // 第三方单号
        $where = [
            'order_no' => $arg['out_trade_no'],
        ];

        $order = OrdersModel::field('id,userid,transaction_id,pay_type,pay_amount,points,vouchers,balance,pay_status,pay_time,activity_parent_order')
            ->where($where)->find();
        // 如果订单是未支付状态
        if ($order && !$order['pay_status']) {
            Distribution::can_offline($order['userid'],0);//判断是否可成为下线
            Distribution::is_distributions($order['userid']);//判断是否可成为分销商
            $member = MembersModel::field('id,role_id,points,vouchers,balance')->where('id', $order['userid'])->find();
            if ($order['pay_type'] == 1) {
                // 微信支付回调，添加第三方支付单号
                $order->transaction_id = $arg['transaction_id'];
            }
            $order->pay_status = 1;
            $order->pay_time   = time();
            if ($order->save()) {
            	$x_where = [
            		'parent_order'=>$order['id']
				];
				$x_order = OrdersModel::field('id,userid,transaction_id,pay_type,pay_amount,points,vouchers,balance,pay_status,pay_time')->where($x_where)->select()->toArray();
				if($x_order){
					foreach ($x_order as $xk =>$xv){
						$u_data = array(
							'id'=>$xv['id'],
							'pay_status'=>1,
							'pay_time'=>time(),
						);
						// 更新订单状态
						OrdersModel::update($u_data);
						// 更新商品销量
						$this->updateGoodsSaleNums($xv['id']);
					}
				}else{
					// 更新商品销量
					$this->updateGoodsSaleNums($order['id']);
				}

                $order = OrdersModel::field('id,userid,transaction_id,pay_type,pay_amount,points,vouchers,balance,pay_status,pay_time,activity_parent_order,group_num')
                    ->where($where)->find();
				if($order['activity_parent_order'] > 0){//判断是否为参团订单
					$a_order_list = OrdersModel::field('id,pay_status')
						->where('activity_parent_order',$order['activity_parent_order'])->select()->toArray();
					if($order['group_num'] == (count($a_order_list)-1)){//判断参团人数是否已满
						$pay_status = 1;
						foreach ($a_order_list as $aik => $aiv){
							if($aiv['pay_status'] == 0){
								$pay_status = 0;
							}
							$order['activity_parent_order'] .=','.$aiv['id'];
						}
						if($pay_status == 1){//判断是否所有成员都已付款
							OrdersModel::where('id','in',$order['activity_parent_order'])->update(['activity_status'=>1]);
						}
					}
				}
                if ($order['pay_type'] == 1) {
                    // 微信支付
                    $member->points = ['inc', $order['pay_amount']];
                    if ($member->save()) {
                        // 积分变动记录
                        MemberPointsModel::create([
                            'order_id'  => $order['id'],
                            'userid'    => $member['id'],
                            'wechat_id' => $order['userid'],
                            'points'    => $order['pay_amount'],
                            'remark'    => '购物赠送积分',
                        ]);
                    }


                }

                if ($order['pay_type'] == 3 && $order['points'] && $member['role_id'] != 2) {
                    // 积分支付
                    $member->points = ['dec', $order['points']];
                    if ($member->save()) {
                        MemberPointsModel::create([
                            'order_id'  => $order['id'],
                            'userid'    => $member['id'],
                            'wechat_id' => $order['userid'],
                            'points'    => -$order['points'],
                            'remark'    => '积分支付',
                        ]);
                    }
                }

                if ($order['pay_type'] == 4 && $order['vouchers'] && $member['role_id'] == 2) {
                    // 抵用券支付
                    $member->vouchers = ['dec', $order['vouchers']];
                    if ($member->save()) {
                        MemberVouchersModel::create([
                            'order_id'  => $order['id'],
                            'userid'    => $member['id'],
                            'wechat_id' => $order['userid'],
                            'vouchers'  => -$order['vouchers'],
                            'remark'    => '抵用券支付',
                        ]);
                    }
                }

                if ($order['pay_type'] == 5 && $order['balance']) {
                    // 余额支付
                    $member->balance = ['dec', $order['balance']];
                    if ($member->save()) {
                        MemberBalanceModel::create([
                            'order_id'  => $order['id'],
                            'userid'    => $member['id'],
                            'wechat_id' => $order['userid'],
                            'balance'   => '-'.$order['balance'],
                            'remark'    => '余额支付',
                            'type'    => 2,
                        ]);

                        $member->points = ['inc', $order['pay_amount']];
                        if ($member->save()) {
                            // 积分变动记录
                            MemberPointsModel::create([
                                'order_id'  => $order['id'],
                                'userid'    => $member['id'],
                                'wechat_id' => $order['userid'],
                                'points'    => $order['pay_amount'],
                                'remark'    => '购物赠送积分',
                            ]);
                        }
                    }
                }
            }
        }
    }


    /**
     * 更新商品销量
     * @param int $order_id 订单 id
     */
    private function updateGoodsSaleNums($order_id)
    {
        $orderGoods  = OrderGoodsModel::field('goods_id,sku_id,goods_nums')->where('order_id', $order_id)->select();
        $goodIds     = [];
        $skuIds      = [];
        $goodsArr    = [];
        $skuArr      = [];
        $activity    = [];//活动商品ID

        foreach ($orderGoods as $v) {
            $goodIds[] = $v['goods_id'];
            $goodsArr[$v['goods_id']] = $v;
            if ($v['sku_id']) {
                $skuIds[] = $v['sku_id'];
                $skuArr[$v['sku_id']] = $v;
            }
        }
        if($activity){
            //ActivityGoods::where('id' ,'in',$activity)->where('is_group',1)->setInc('group_sale',1);//拼团活动人数自增
        }

        // 订单商品信息
        $where = [
            ['id', 'in', $goodIds],
        ];
        $goods = GoodsModel::field('id,diy_sale_nums,actual_sale_nums')->where($where)->select();

        // 订单商品 sku 信息
        $where = [
            ['id', 'in', $skuIds],
        ];
        $sku = GoodSkuModel::field('id,sale_nums')->where($where)->select();

        $updateGoods = [];
        foreach ($goods as $v) {
            $updateGoods[] = [
                'id'               => $v['id'],
                'diy_sale_nums'    => $v['diy_sale_nums'] + $goodsArr[$v['id']]['goods_nums'],
                'actual_sale_nums' => $v['actual_sale_nums'] + $goodsArr[$v['id']]['goods_nums'],
            ];
        }

        $updateSku = [];
        foreach ($sku as $v) {
            $updateSku[] = [
                'id'        => $v['id'],
                'sale_nums' => $v['sale_nums'] + $skuArr[$v['id']]['goods_nums'],
            ];
        }

        (new GoodsModel)->saveAll($updateGoods);
        (new GoodSkuModel)->saveAll($updateSku);
    }


    /**

     * 微信退款

     * @param  array $data 订单信息

     */

    public function refund($data)

    {

        $tools      = new JsApiPay();

//         $total_fee  = (float)$data['pay_amount'] * 100;
        $total_fee  = 1;

        $input = new WxPayRefund();

        $input->SetOut_trade_no("{$data['out_trade_no']}");
        $input->SetOut_refund_no("{$data['transaction_id']}");

        $input->SetTotal_fee("{$total_fee}");

        $input->SetRefund_fee("{$total_fee}");

        $input->SetOp_user_id(config('site.mch_id'));

        $order = WxPayApi::refund($input);


        dump($order);

    }

}
